/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package NicholasServlets;

import NicholasValueBeans.VotingList;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author ChuckToh
 */
public class processNewVotingList extends HttpServlet {

    private String voteTopicsParameter = "voteTopics";
    private String voteDateStartParameter = "dateStart";
    private String voteDateEndParameter = "dateEnd";
    private String dateRegex = "....-..-..";
    private String location = "/Nicholas/Nicholasindex.jsp#tabs-3";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String afterNewVotingListMessage = "";
        HttpSession session = request.getSession();
        try {
            String voteTopics = request.getParameter(voteTopicsParameter);
            String dateStartStr = request.getParameter(voteDateStartParameter);
            String dateEndStr = request.getParameter(voteDateEndParameter);

            if (isNullOrEmpty(voteTopics) || isNullOrEmpty(dateStartStr) || isNullOrEmpty(dateEndStr)) {
                afterNewVotingListMessage = "<font color='red'>Required fields are not filled in!</font>";
            } else {
                if (isDateFormat(dateStartStr) && isDateFormat(dateEndStr)) {
                    Date dateStart = convertStrToDate(dateStartStr);
                    Date dateEnd = convertStrToDate(dateEndStr);

                    Calendar cal = Calendar.getInstance();
                    String time = String.format("%02d", cal.get(Calendar.YEAR)) + "-" + String.format("%02d", cal.get(Calendar.MONTH) + 1) + "-" + String.format("%02d", cal.get(Calendar.DAY_OF_MONTH));
                    Date today = convertStrToDate(time);

                    if (dateStart.getTime() < today.getTime()) {
                        afterNewVotingListMessage = "<font color='red'>Vote start date cannot be earlier than today!</font>";
                    } else if (dateEnd.getTime() < dateStart.getTime()) {
                        afterNewVotingListMessage = "<font color='red'>Vote end date cannot be earlier than vote start date!</font>";
                    } else {
                        VotingList vl = new VotingList();
                        vl.setVoteTopics(voteTopics);
                        vl.setDateCreated(today);
                        vl.setDateStart(dateStart);
                        vl.setDateEnd(dateEnd);

                        if (vl.ongoingVotingList()) {
                            afterNewVotingListMessage = "<font color='red'>There are votes that have not end before the commencing date of this new voting list!</font>";
                        } else {
                            if (vl.insertVotingList()) {
                                afterNewVotingListMessage = "The new voting list has been uploaded!";
                            } else {
                                afterNewVotingListMessage = "<font color='red'>Out apologies! And error has occurred in creating the new voting list!</font>";
                            }
                        }
                    }
                } else {
                    afterNewVotingListMessage = "<font color='red'>Please follow the date format!</font>";
                }
            }
        } finally {
            session.setAttribute("afterNewVotingListMessage", afterNewVotingListMessage);
            response.sendRedirect(request.getContextPath() + location);
            out.close();
        }
    }

    private boolean isDateFormat(String dateStr) {
        boolean isDate = false;

        if (dateStr.matches(dateRegex)) {
            isDate = true;
        }

        return isDate;
    }

    private Date convertStrToDate(String dateStr) {
        Date date = null;

        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date tempDate = df.parse(dateStr);
            date = new Date(tempDate.getTime());
        } catch (ParseException ex) {
            System.out.println(ex.getMessage());
        }

        return date;
    }

    private boolean isNullOrEmpty(String data) {
        boolean isNullOrEmpty = true;

        if (data != null && !data.isEmpty()) {
            isNullOrEmpty = false;
        }

        return isNullOrEmpty;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
